package com.bdqn.jwt1.util;

import com.bdqn.jwt1.entity.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component("jwtLoginSuccessHandler")
public class JwtLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String token = JwtUtil.generateToken(authentication);
        response.setContentType("application/json;charset=UTF-8");
        ResponseResult sr = new ResponseResult();
        sr.setCode(1);
        sr.setAuthorization(token);
        sr.setFlag(true);
        String s = objectMapper.writeValueAsString(sr);
        response.getWriter().write(s);
    }
}
